package org.swift.mashup.engine.deployment.mcr;

import org.apache.axis2.context.MessageContext;
import org.apache.axis2.transport.http.HTTPConstants;
import org.swift.mashup.engine.deployment.MessageContextReader;

import javax.servlet.ServletRequest;
import java.util.*;

public class RequestAttributesMessageContextReader implements MessageContextReader {

	private final static String X509_CERT_ATTRIBUTE_NAME = "javax.servlet.request.X509Certificate";

	private static RequestAttributesMessageContextReader instance = null;

	public static RequestAttributesMessageContextReader getInstance() {
		if (instance == null) {
			instance = new RequestAttributesMessageContextReader();
		}
		return instance;
	}

	private RequestAttributesMessageContextReader() {
	}

	@Override
	public Map<String, Object> createParameterMap(MessageContext context) {
		Map<String, Object> map = new HashMap<String,Object>();
		ServletRequest req = (ServletRequest) context.getProperty(HTTPConstants.MC_HTTP_SERVLETREQUEST);
		Enumeration<String> attrs = req.getAttributeNames();

		while(attrs.hasMoreElements()){
			String name = attrs.nextElement();
			Object value = req.getAttribute(name);
			if(X509_CERT_ATTRIBUTE_NAME.equals(name)) {
				// FIXME: serialize this array as XML and add it that way
				continue;
			}
			if(value instanceof Collection){
				Collection coll = (Collection)value;
				if ( coll.size() == 1 ) {
					value = coll.iterator().next();
				}
			}

			map.put(name, value);
		}

		return map;
	}
}
